package com.edushare.common.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class UploadUtils {
	
	private static final Log log = LogFactory.getLog(UploadUtils.class);
	
	/** returns complete path for storing data to storage */
	public static String getMediaUploadPath(){
		
		String path = null;
		String storageRootDirectory = SystemUtils.getMediaDirectoryPath(false);
		String separator = System.getProperties().getProperty("file.separator");
		Date today = new Date();
		String yearFolder = new SimpleDateFormat("yyyy").format(today);
		String monthFolder = new SimpleDateFormat("MM").format(today);
		String dayFolder = new SimpleDateFormat("yyyy-MM-dd").format(today);
		path = storageRootDirectory
					+separator+yearFolder
					+separator+monthFolder
					+separator+dayFolder;
		log.debug("Upload Path: "+path);
		File directory = new File(path);
		if(!directory.exists())
			directory.mkdirs();
		return path;
	}
	
	public static String getRelativeUploadPath(String absoluteFilePath){
		String baseDirectory = SystemUtils.getRootDirectoryPath();
		String relativePath = "";
		if(absoluteFilePath.startsWith(baseDirectory)){
			relativePath = absoluteFilePath.substring(baseDirectory.length());
		}
		relativePath = relativePath.replace('\\', '/');
		if(relativePath.startsWith("/")){
			relativePath = relativePath.substring(1);
		}
		
		if(!StringUtil.isValid(relativePath)){
			log.warn("RELATIVE PATH FOR UPLOADED FILE IS NOT APPROPRIATE.");
		}
		
		return relativePath;
	}
	
	/** Always returns <b>JPEG</b> file name that's created by media processor */
	public static String getImagePath(String origFilePath, String suffix){
		if(!StringUtil.isValid(origFilePath))
			throw new IllegalArgumentException("OrigFilePath cant be null or empty.");
		if(!StringUtil.isValid(suffix)){
			suffix = "";
		}
		
		return origFilePath.substring(0, origFilePath.lastIndexOf(".")) +"_" +suffix + ".jpg";
	}

}
